<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button @click="handleAdd" type="primary" icon="plus">新增</a-button>
      <a-button type="primary" icon="download" @click="handleExportXls('出库单明细')">导出</a-button>
      <a-upload name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader" :action="importExcelUrl" @change="handleImportExcel">
        <a-button type="primary" icon="import">导入</a-button>
      </a-upload>
      <!-- 高级查询区域 -->
      <j-super-query :fieldList="superFieldList" ref="superQueryModal" @handleSuperQuery="handleSuperQuery"></j-super-query>
      <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="batchDel"><a-icon type="delete"/>删除</a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px"> 批量操作 <a-icon type="down" /></a-button>
      </a-dropdown>
    </div>

    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a style="font-weight: 600">{{ selectedRowKeys.length }}</a>项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>

      <a-table
        ref="table"
        size="middle"
        rowKey="id"
        class="j-table-force-nowrap"
        :scroll="{x:true}"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :expandedRowKeys="expandedRowKeys"
        @change="handleTableChange"
        @expand="handleExpand"
        v-bind="tableProps">

        <template slot="imgSlot" slot-scope="text,record">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无图片</span>
          <img v-else :src="getImgView(text)" :preview="record.id" height="25px" alt="" style="max-width:80px;font-size: 12px;font-style: italic;"/>
        </template>
        <template slot="fileSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无文件</span>
          <a-button
            v-else
            :ghost="true"
            type="primary"
            icon="download"
            size="small"
            @click="downloadFile(text)">
            下载
          </a-button>
        </template>

        <span slot="action" slot-scope="text, record">
          <a @click="handleEdit(record)">编辑</a>

          <a-divider type="vertical" />
          <a-dropdown>
            <a class="ant-dropdown-link">更多 <a-icon type="down" /></a>
            <a-menu slot="overlay">
              <a-menu-item>
                <a @click="handleAddChild(record)">添加下级</a>
              </a-menu-item>
              <a-menu-item>
                <a-popconfirm title="确定删除吗?" @confirm="() => handleDeleteNode(record.id)" placement="topLeft">
                  <a>删除</a>
                </a-popconfirm>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </span>

      </a-table>
    </div>

    <bussProductOutboundOrderDetail-modal ref="modalForm" @ok="modalFormOk"></bussProductOutboundOrderDetail-modal>
  </a-card>
</template>

<script>

import { getAction, deleteAction } from '@/api/manage'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import BussProductOutboundOrderDetailModal from './modules/BussProductOutboundOrderDetailModal'
import {filterMultiDictText} from '@/components/dict/JDictSelectUtil'
import { filterObj } from '@/utils/util';

export default {
  name: "BussProductOutboundOrderDetailList",
  mixins:[JeecgListMixin],
  components: {
    BussProductOutboundOrderDetailModal
  },
  data () {
    return {
      description: '出库单明细管理页面',
      // 表头
      columns: [
        {
          title:'物料名称',
          align:"left",
          dataIndex: 'materialName'
        },
        {
          title:'出库信息ID',
          align:"left",
          dataIndex: 'informationId'
        },
        {
          title:'物料ID',
          align:"left",
          dataIndex: 'materialId'
        },
        {
          title:'物料编号',
          align:"left",
          dataIndex: 'materialCode'
        },
        {
          title:'规格型号',
          align:"left",
          dataIndex: 'noneSpec'
        },
        {
          title:'主计量',
          align:"left",
          dataIndex: 'meUnit_dictText'
        },
        {
          title:'数量',
          align:"left",
          dataIndex: 'quantity'
        },
        {
          title:'批次号',
          align:"left",
          dataIndex: 'batchNumber'
        },
        {
          title:'物料批号',
          align:"left",
          dataIndex: 'materialBatchNumber'
        },
        {
          title:'库位',
          align:"left",
          dataIndex: 'warehouseLocation'
        },
        {
          title:'入库数量',
          align:"left",
          dataIndex: 'inventoryQuantity'
        },
        {
          title:'已出数量',
          align:"left",
          dataIndex: 'outputQuantity'
        },
        {
          title:'宝洁供应商编码',
          align:"left",
          dataIndex: 'bjSupplierCode'
        },
        {
          title:'宝洁供应商',
          align:"left",
          dataIndex: 'bjSupplierName'
        },
        {
          title:'入库ID',
          align:"left",
          dataIndex: 'warehousingId'
        },
        {
          title:'入库单号',
          align:"left",
          dataIndex: 'warehousingCode'
        },
        {
          title:'入库日期',
          align:"left",
          dataIndex: 'warehousingDate'
        },
        {
          title:'限用日期',
          align:"left",
          dataIndex: 'restrictedDate'
        },
        {
          title:'宝洁单号',
          align:"left",
          dataIndex: 'bjNo'
        },
        {
          title:'占用数量',
          align:"left",
          dataIndex: 'occupationQuantity'
        },
        {
          title:'辅助单位',
          align:"left",
          dataIndex: 'auUnit_dictText'
        },
        {
          title:'辅助数量',
          align:"left",
          dataIndex: 'auQuantity'
        },
        {
          title:'入库辅助数量',
          align:"left",
          dataIndex: 'inAuQuantity'
        },
        {
          title:'已出辅助数量',
          align:"left",
          dataIndex: 'outAuQuantity'
        },
        {
          title:'占用辅助数量',
          align:"left",
          dataIndex: 'occupationAuQuantity'
        },
        {
          title:'单位换算率',
          align:"left",
          dataIndex: 'conversionRate'
        },
        {
          title:'供应商',
          align:"left",
          dataIndex: 'supplierId_dictText'
        },
        {
          title:'生产车间',
          align:"left",
          dataIndex: 'productionWorkshop_dictText'
        },
        {
          title:'客户名称',
          align:"left",
          dataIndex: 'customerName'
        },
        {
          title:'备注',
          align:"left",
          dataIndex: 'remark'
        },
        {
          title:'订单编号',
          align:"left",
          dataIndex: 'orderNo'
        },
        {
          title: '操作',
          dataIndex: 'action',
          align:"center",
          fixed:"right",
          width:147,
          scopedSlots: { customRender: 'action' },
        }
      ],
      url: {
        list: "/outbound/bussProductOutboundOrderDetail/rootList",
        childList: "/outbound/bussProductOutboundOrderDetail/childList",
        getChildListBatch: "/outbound/bussProductOutboundOrderDetail/getChildListBatch",
        delete: "/outbound/bussProductOutboundOrderDetail/delete",
        deleteBatch: "/outbound/bussProductOutboundOrderDetail/deleteBatch",
        exportXlsUrl: "/outbound/bussProductOutboundOrderDetail/exportXls",
        importExcelUrl: "outbound/bussOutboundOrderDetail/importExcel",
      },
      expandedRowKeys:[],
      hasChildrenField:"hasChild",
      pidField:"pid",
      dictOptions: {},
      loadParent: false,
      superFieldList:[],
    }
  },
  created() {
    this.getSuperFieldList();
  },
  computed: {
    importExcelUrl(){
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
    },
    tableProps() {
      let _this = this
      return {
        // 列表项是否可选择
        rowSelection: {
          selectedRowKeys: _this.selectedRowKeys,
          onChange: (selectedRowKeys) => _this.selectedRowKeys = selectedRowKeys
        }
      }
    }
  },
  methods: {
    loadData(arg){
      if(arg==1){
        this.ipagination.current=1
      }
      this.loading = true
      let params = this.getQueryParams()
      params.hasQuery = 'true'
      getAction(this.url.list,params).then(res=>{
        if(res.success){
          let result = res.result
          if(Number(result.total)>0){
            this.ipagination.total = Number(result.total)
            this.dataSource = this.getDataByResult(res.result.records)
            return this.loadDataByExpandedRows(this.dataSource)
          }else{
            this.ipagination.total=0
            this.dataSource=[]
          }
        }else{
          this.$message.warning(res.message)
        }
      }).finally(()=>{
        this.loading = false
      })
    },
    // 根据已展开的行查询数据（用于保存后刷新时异步加载子级的数据）
    loadDataByExpandedRows(dataList) {
      if (this.expandedRowKeys.length > 0) {
        return getAction(this.url.getChildListBatch,{ parentIds: this.expandedRowKeys.join(',') }).then(res=>{
          if (res.success && res.result.records.length>0) {
            //已展开的数据批量子节点
            let records = res.result.records
            const listMap = new Map();
            for (let item of records) {
              let pid = item[this.pidField];
              if (this.expandedRowKeys.join(',').includes(pid)) {
                let mapList = listMap.get(pid);
                if (mapList == null) {
                  mapList = [];
                }
                mapList.push(item);
                listMap.set(pid, mapList);
              }
            }
            let childrenMap = listMap;
            let fn = (list) => {
              if (list) {
                list.forEach(data => {
                  if (this.expandedRowKeys.includes(data.id)) {
                    data.children = this.getDataByResult(childrenMap.get(data.id))
                    fn(data.children)
                  }
                })
              }
            }
            fn(dataList)
          }
        })
      } else {
        return Promise.resolve()
      }
    },
    getQueryParams(arg) {
      //获取查询条件
      let sqp = {}
      let param = {}
      if (this.superQueryParams) {
        sqp['superQueryParams'] = encodeURI(this.superQueryParams)
        sqp['superQueryMatchType'] = this.superQueryMatchType
      }
      if (arg) {
        param = Object.assign(sqp, this.isorter, this.filters);
      } else {
        param = Object.assign(sqp, this.queryParam, this.isorter, this.filters);
      }
      if (JSON.stringify(this.queryParam) === "{}" || arg) {
        param.hasQuery = 'false'
      } else {
        param.hasQuery = 'true'
      }
      param.field = this.getQueryField();
      param.pageNo = this.ipagination.current;
      param.pageSize = this.ipagination.pageSize;
      return filterObj(param);
    },
    searchReset() {
      //重置
      this.expandedRowKeys = []
      this.queryParam = {}
      this.loadData(1);
    },
    getDataByResult(result) {
      if (result) {
        return result.map(item => {
          //判断是否标记了带有子节点
          if (item[this.hasChildrenField] == '1') {
            let loadChild = { id: item.id + '_loadChild', name: 'loading...', isLoading: true }
            item.children = [loadChild]
          }
          return item
        })
      }
    },
    handleExpand(expanded, record) {
      // 判断是否是展开状态
      if (expanded) {
        this.expandedRowKeys.push(record.id)
        if (record.children.length > 0 && record.children[0].isLoading === true) {
          let params = this.getQueryParams(1);//查询条件
          params[this.pidField] = record.id
          params.hasQuery = 'false'
          params.superQueryParams = ""
          getAction(this.url.childList, params).then((res) => {
            if (res.success) {
              if (res.result.records) {
                record.children = this.getDataByResult(res.result.records)
                this.dataSource = [...this.dataSource]
              } else {
                record.children = ''
                record.hasChildrenField = '0'
              }
            } else {
              this.$message.warning(res.message)
            }
          })
        }
      } else {
        let keyIndex = this.expandedRowKeys.indexOf(record.id)
        if (keyIndex >= 0) {
          this.expandedRowKeys.splice(keyIndex, 1);
        }
      }
    },
    handleAddChild(record) {
      this.loadParent = true
      let obj = {}
      obj[this.pidField] = record['id']
      this.$refs.modalForm.add(obj);
    },
    handleDeleteNode(id) {
      if (!this.url.delete) {
        this.$message.error("请设置url.delete属性!")
        return
      }
      var that = this;
      deleteAction(that.url.delete, { id: id }).then((res) => {
        if (res.success) {
          that.loadData(1)
        } else {
          that.$message.warning(res.message);
        }
      });
    },
    batchDel() {
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning('请选择一条记录！');
        return false;
      } else {
        let ids = "";
        let that = this;
        that.selectedRowKeys.forEach(function(val) {
          ids += val + ",";
        });
        that.$confirm({
          title: "确认删除",
          content: "是否删除选中数据?",
          onOk: function() {
            that.handleDeleteNode(ids)
            that.onClearSelected();
          }
        });
      }
    },
    getSuperFieldList() {
      let fieldList = [];
      fieldList.push({ type: 'string', value: 'informationId', text: '出库信息ID', dictCode: '' })
      fieldList.push({ type: 'string', value: 'materialId', text: '物料ID', dictCode: '' })
      fieldList.push({ type: 'string', value: 'materialCode', text: '物料编号', dictCode: '' })
      fieldList.push({ type: 'string', value: 'materialName', text: '物料名称', dictCode: '' })
      fieldList.push({ type: 'string', value: 'noneSpec', text: '规格型号', dictCode: '' })
      fieldList.push({ type: 'string', value: 'meUnit', text: '主计量', dictCode: 'ji_unit' })
      fieldList.push({ type: 'BigDecimal', value: 'quantity', text: '数量', dictCode: '' })
      fieldList.push({ type: 'string', value: 'batchNumber', text: '批次号', dictCode: '' })
      fieldList.push({ type: 'string', value: 'materialBatchNumber', text: '物料批号', dictCode: '' })
      fieldList.push({ type: 'string', value: 'warehouseLocation', text: '库位', dictCode: '' })
      fieldList.push({ type: 'BigDecimal', value: 'inventoryQuantity', text: '入库数量', dictCode: '' })
      fieldList.push({ type: 'BigDecimal', value: 'outputQuantity', text: '已出数量', dictCode: '' })
      fieldList.push({ type: 'string', value: 'bjSupplierCode', text: '宝洁供应商编码', dictCode: '' })
      fieldList.push({ type: 'string', value: 'bjSupplierName', text: '宝洁供应商', dictCode: '' })
      fieldList.push({ type: 'string', value: 'warehousingId', text: '入库ID', dictCode: '' })
      fieldList.push({ type: 'string', value: 'warehousingCode', text: '入库单号', dictCode: '' })
      fieldList.push({ type: 'datetime', value: 'warehousingDate', text: '入库日期' })
      fieldList.push({ type: 'datetime', value: 'restrictedDate', text: '限用日期' })
      fieldList.push({ type: 'string', value: 'bjNo', text: '宝洁单号', dictCode: '' })
      fieldList.push({ type: 'BigDecimal', value: 'occupationQuantity', text: '占用数量', dictCode: '' })
      fieldList.push({ type: 'string', value: 'auUnit', text: '辅助单位', dictCode: 'zl_unit' })
      fieldList.push({ type: 'BigDecimal', value: 'auQuantity', text: '辅助数量', dictCode: '' })
      fieldList.push({ type: 'BigDecimal', value: 'inAuQuantity', text: '入库辅助数量', dictCode: '' })
      fieldList.push({ type: 'BigDecimal', value: 'outAuQuantity', text: '已出辅助数量', dictCode: '' })
      fieldList.push({ type: 'BigDecimal', value: 'occupationAuQuantity', text: '占用辅助数量', dictCode: '' })
      fieldList.push({ type: 'string', value: 'conversionRate', text: '单位换算率', dictCode: '' })
      fieldList.push({ type: 'string', value: 'supplierId', text: '供应商', dictCode: "erp_supplier,name,id" })
      fieldList.push({
        type: 'string',
        value: 'productionWorkshop',
        text: '生产车间',
        dictCode: "sys_depart,depart_name,id"
      })
      fieldList.push({ type: 'string', value: 'customerName', text: '客户名称', dictCode: '' })
      fieldList.push({ type: 'Text', value: 'remark', text: '备注', dictCode: '' })
      fieldList.push({ type: 'string', value: 'orderNo', text: '订单编号', dictCode: '' })
      fieldList.push({ type: 'string', value: 'pid', text: '父级节点', dictCode: '' })
      this.superFieldList = fieldList
    }
  }
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>